/**
 * form表单操作工具
 */
import { castArray } from 'lodash-unified'
import { Arrayable } from '../../../../utils'
import { FormItemContext, FormItemValidateState, FormErrorType, FormErrorTypeArray } from '../../../../types/tn-form'

/**
 * 过滤符合条件的Field
 * @param fields formitem容器内容
 * @param props formitemProp参数
 */
export const filterFields = (
  fields: FormItemContext[],
  props: Arrayable<Arrayable<string>>
) => {
  const normalized = castArray(props)
  return normalized.length > 0
    ? fields.filter((field) => field.prop && normalized.includes(field.prop))
    :fields
}

/**
 * 是否显示错误信息
 * @param errorType 错误提示方式
 * @param state 校验状态
 * @param type 当前提示类型
 * @returns 显示错误的状态
 */
export const showValidateError = (errorType: FormErrorTypeArray,state: FormItemValidateState, type: FormErrorType): boolean => {
  if (state === 'error') {
    if (type === 'none' || type.includes('none')) return false
    if (Array.isArray(errorType)) {
      return errorType.includes(type)
    } else {
      return errorType === type
    }
  }
  return false
}